package com.xaicode.algorithm.leetcode._1_100;

import com.xaicode.utils.Random;
import com.xaicode.utils.Stopwatch;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <a href="https://leetcode-cn.com/problems/two-sum">两数之和</a>
 *
 * <p>给定一个整数数组 <code>nums</code> 和一个整数目标值 <code>target</code>，请你在该数组中找出 <strong>和为目标值</strong> 的那 <strong>两个</strong> 整数，并返回它们的数组下标。</p>
 *
 * <p>你可以假设每种输入只会对应一个答案。但是，数组中同一个元素在答案里不能重复出现。</p>
 *
 * <p>你可以按任意顺序返回答案。</p>
 *
 * <p> </p>
 *
 * <p><strong>示例 1：</strong></p>
 *
 * <pre>
 * <strong>输入：</strong>nums = [2,7,11,15], target = 9
 * <strong>输出：</strong>[0,1]
 * <strong>解释：</strong>因为 nums[0] + nums[1] == 9 ，返回 [0, 1] 。
 * </pre>
 *
 * <p><strong>示例 2：</strong></p>
 *
 * <pre>
 * <strong>输入：</strong>nums = [3,2,4], target = 6
 * <strong>输出：</strong>[1,2]
 * </pre>
 *
 * <p><strong>示例 3：</strong></p>
 *
 * <pre>
 * <strong>输入：</strong>nums = [3,3], target = 6
 * <strong>输出：</strong>[0,1]
 * </pre>
 *
 * <p> </p>
 *
 * <p><strong>提示：</strong></p>
 *
 * <ul>
 * 	<li><code>2 <= nums.length <= 10<sup>3</sup></code></li>
 * 	<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
 * 	<li><code>-10<sup>9</sup> <= target <= 10<sup>9</sup></code></li>
 * 	<li><strong>只会存在一个有效答案</strong></li>
 * </ul>
 *
 * @author beborn xaicode@sina.com
 */
@Slf4j
public class _1_Easy_TwoSum {

    public static void main(String[] args) {

        int[] array = Random.INT_ARR_0_9;
        int target = 9;

        long time = Stopwatch.elapsedTime(() -> {
            _1_Easy_TwoSum easy_twoSum = new _1_Easy_TwoSum();

            int[] result = easy_twoSum.twoSum(array, target);

            log.info("result array index is {}", Arrays.toString(result));
            return null;
        });

        log.info("cost {} mills", time);
    }

    /**
     * 执行耗时:2 ms,击败了63.39% 的Java用户
     * 内存消耗:38.6 MB,击败了52.13% 的Java用户
     */
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0, n = nums.length; i < n; ++i) {
            int num = target - nums[i];
            if (map.containsKey(num)) {
                return new int[]{map.get(num), i};
            }
            map.put(nums[i], i);
        }
        return null;
    }

}
